import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import AuthAPI from '@/api/login/AuthAPI'

// 用户信息接口
export interface UserInfo {
  userId: string | number;
  username: string;
  realName: String;
  stationId: String;
  telephone: String;
}

// 用户状态管理
export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  const menus = ref<Array<any>>([])
  const permissions = ref<Array<string>>([])
  const isLoggedIn = ref<boolean>(false)

  // 计算属性
  const hasToken = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.username || '')

  // 登录
  const login = async (loginData: { username: string; password: string }) => {
    try {
      const response = await AuthAPI.login(loginData.username, loginData.password);
      if (response.code !== '00') {
        return { success: false, message: response.message }
      }
      const res = response.data;

      setToken(res.token)
      setUserInfo(res.userInfo)
      setMenus(res.menus)
      setPermissions(res.permissions)
      setLoginStatus(true)

      // 持久化存储
      uni.setStorageSync('token', res.token);
      uni.setStorageSync('refreshToken', res.refreshToken);
      uni.setStorageSync('userInfo', res.userInfo);
      uni.setStorageSync('menus', res.menus);
      uni.setStorageSync('permissions', res.permissions);

      return { success: true, data: response }
    } catch (error: any) {
      console.error('登录失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 退出登录
  const logout = async () => {
    const refreshToken = uni.getStorageSync("refreshToken");
    await AuthAPI.logout(refreshToken)

    setToken('')
    setUserInfo(null)
    setMenus([])
    setPermissions([])
    setLoginStatus(false)

    // 清除本地存储
    uni.removeStorageSync('token')
    uni.removeStorageSync('refreshToken')
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('menus')
    uni.removeStorageSync('permissions')

    // 可以在这里添加跳转到登录页的逻辑
    uni.reLaunch({ url: '/pages/login/login' })
  }

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
  }

  // 设置用户信息
  const setUserInfo = (info: UserInfo | null) => {
    userInfo.value = info
  }

  // 设置登录状态
  const setLoginStatus = (status: boolean) => {
    isLoggedIn.value = status
  }

  // 设置菜单列表
  const setMenus = (mlist: Array<any>) => {
    menus.value = mlist;
  }

  // 设置权限列表
  const setPermissions = (plist: Array<string>) => {
    permissions.value = plist;
  }

  // 更新用户信息
  const updateUserInfo = (info: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...info }
      uni.setStorageSync('userInfo', userInfo.value)
    }
  }

  // 初始化用户状态（从本地存储恢复）
  const initUserState = () => {
    try {
      const savedToken = uni.getStorageSync('token')
      const savedUserInfo = uni.getStorageSync('userInfo')
      const savedMenus = uni.getStorageSync('menus')
      const savedPermissions = uni.getStorageSync('permissions')

      if (savedToken) {
        setToken(savedToken)
        setLoginStatus(true)
      }

      if (savedUserInfo) {
        setUserInfo(savedUserInfo)
      }
      if (savedMenus) {
        setMenus(savedMenus) 
      }
      if (savedPermissions) {
        setPermissions(savedPermissions) 
      }
    } catch (error) {
      console.error('初始化用户状态失败:', error)
    }
  }

  return {
    // 状态
    token,
    userInfo,
    menus,
    permissions,
    isLoggedIn,
    
    // 计算属性
    hasToken,
    userName,
    
    // 方法
    login,
    logout,
    setToken,
    setUserInfo,
    setMenus,
    setPermissions,
    setLoginStatus,
    updateUserInfo,
    initUserState
  }
})